# 订单信息
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from datetime import datetime

from myadmin.models import Orders, OrdersDetail, Payment, User, Member


def index(request, pIndex=1):
    """ 浏览订单 """
    # 获取当前店铺id号
    sid = request.session['shopinfo']['id']
    olist = Orders.objects.filter(shop_id=sid)

    # 搜索条件
    mywhere = []
    status = request.GET.get('status', '')
    if status != '':
        olist = olist.filter(status=status)
        mywhere.append('status=' + status)

    olist = olist.order_by('-id')  # 排序
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(olist, 10)  # 5条数据一页显示
    maxpages = page.num_pages  # 获取最大页数
    # 判断不能越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 获取当前页数据
    plist = page.page_range  # 获取页码列表信息

    for vo in list2:
        if vo.user_id == 0:
            vo.nickname = '无'
        else:
            user = User.objects.only('nickname').get(id=vo.user_id)
            vo.nickname = user.nickname

        if vo.member_id == 0:
            vo.member_name = '大堂顾客'
        else:
            member = Member.objects.only('mobile').get(id=vo.member_id)
            vo.member_name = member.mobile

    o1 = len(Orders.objects.filter(status=1))
    o2 = len(Orders.objects.filter(status=2))
    o3 = len(Orders.objects.filter(status=3))

    context = {
        'orderslist': list2,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'sum': [o1, o2, o3],
        'sta': status
    }
    return render(request, 'web/list.html', context)


def insert(request):
    """ 执行添加 """
    try:
        # print(request.session.get('shopinfo'))
        # 订单信息添加
        od = Orders()
        od.shop_id = request.session['shopinfo']['id']
        od.member_id = 0
        od.user_id = request.session['webuser']['id']
        od.money = request.session['total_money']
        od.status = 1  # 1进行中/2无效/3已完成
        od.payment_status = 2  # 1未支付/2已支付/3已退款
        od.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        od.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        od.save()

        # 支付信息添加
        op = Payment()
        op.order_id = od.id  # 订单id号
        op.member_id = 0
        op.type = 2
        op.bank = request.GET.get('bank', 3)  # 1微信/2余额/3现金/4支付宝
        op.money = request.session['total_money']
        op.status = 1  # 1未支付/2已支付/3已退款
        op.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        op.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        op.save()

        # 订单详情的添加
        cart_list = request.session.get('cart_list', {})  # 获取购物车中的菜品信息
        # 遍历购物车中的菜品信息 添加到订单详情中
        for item in cart_list.values():
            ov = OrdersDetail()
            ov.order_id = od.id  # 订单id
            ov.product_id = item['id']  # 菜品id
            ov.product_name = item['name']  # 菜品名称
            ov.price = item['price']  # 菜品单价
            ov.quantity = item['num']  # 菜品数量
            ov.status = 1  # 状态  1正常/9删除
            ov.save()

        # 成功后清空购物车和总金额
        del request.session['cart_list']
        del request.session['total_money']

        return HttpResponse("Y")

    except Exception as arr:
        print(arr, 1)
        return HttpResponse("N")


def detail(request):
    """ 加载订单详情 """
    oid = request.GET.get('oid', 0)

    dlist = OrdersDetail.objects.filter(order_id=oid)
    return render(request, 'web/detail.html', {'detail_list': dlist})


def status(request):
    """ 修改订单状态 """
    oid = request.GET.get('oid', 0)
    ob = Orders.objects.get(id=oid)
    ob.status = request.GET['status']
    ob.save()
    return HttpResponse('Y')
